package com.cheng.spring04.service.impl;

import com.cheng.spring04.dao.BookDao;
import com.cheng.spring04.dao.UserDao;
import com.cheng.spring04.service.BookService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;

import java.util.concurrent.TimeUnit;

@Service
public class BookServiceImpl implements BookService {

    private final BookDao bookDao;

    private final UserDao userDao;

    public BookServiceImpl(BookDao bookDao, UserDao userDao) {
        this.bookDao = bookDao;
        this.userDao = userDao;
    }

    // @Transactional开启事务控制，可放在类、方法上
    // 属性：timeout设置超时时间单位秒，若超时自动回滚
    //      noRollbackFor设置出现指定异常时不会回滚，值为class
    //      noRollbackForClassName设置出现指定异常时不会回滚，值为类的全类名
    //      isolation设置事务的隔离级别默认Isolation.DEFAULT
    @Transactional(timeout = 3,isolation = Isolation.DEFAULT)
    @Override
    public void buyBook(int bookId, int userId, int num) {
        // 查询价格
        Integer price = bookDao.queryBookPriceById(bookId);
        // try {
        //     TimeUnit.SECONDS.sleep(5);
        // } catch (InterruptedException e) {
        //     throw new RuntimeException(e);
        // }
        // 修改库存
        bookDao.updateBookStockById(bookId, num);
        // 修改用户余额
        userDao.updateUserBalanceByUserId(userId, price);
    }


}
